package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.company.entity.Remind;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.RemindService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.oa.core.entity.com.AllChange;
import com.fz.us.oa.core.entity.com.PersonnelInfo;
import com.fz.us.oa.core.entity.com.PersonnelUse;
import com.fz.us.oa.core.entity.com.Renewal;
import com.fz.us.oa.core.service.com.AllChangeService;
import com.fz.us.oa.core.service.com.PersonnelInfoService;
import com.fz.us.oa.core.service.com.PersonnelUseService;
import com.fz.us.oa.core.service.com.RenewalService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ZhuChunXiao on 2017/7/17.
 */
@Controller
@RequestMapping(value = "/com/renewal")
public class RenewalController extends BaseController {
    private static final long serialVersionUID = 1328920169535647246L;

    @Autowired
    private RenewalService renewalService;
    @Autowired
    private PersonnelInfoService personnelInfoService;
    @Autowired
    private AllChangeService allChangeService;
    @Autowired
    private PersonnelUseService personnelUseService;
    @Autowired
    private TaskEntityService taskEntityService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private RemindService remindService;

    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String parentId,String draft,String index,String todo,String remind,String record) {
        if (StringUtils.isNotEmpty(keyId)){
            Renewal renewal=renewalService.get(keyId);
            model.addAttribute("keyId", keyId);
            model.addAttribute("renewal", renewal);
        }
        PersonnelInfo personnelInfo=personnelInfoService.get(parentId);
        model.addAttribute("parentId", parentId);
        model.addAttribute("personnelInfo", personnelInfo);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/renewal_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            Renewal renewal=renewalService.get(keyId);
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            int stepNo = taskEntity.getStepNo();
            String isEdit =  isEdit(keyId);
            model.addAttribute("isEdit", isEdit);
            model.addAttribute("renewal", renewal);
            model.addAttribute("stepNo", stepNo);
        }
        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/renewal_read";
    }

    /**
     * 从异动总汇进入只读页面
     */
    @RequestMapping(value = "toRead",method = RequestMethod.GET,produces = MediaType.TEXT_HTML_VALUE)
    public String toRead(@CurrentUser User user, Model model,String allChangeId,String keyId,String draft,String index,String todo,String remind,String record){
        AllChange allChange=allChangeService.get(allChangeId);
        Renewal renewal=allChange.getRenewal();
        TaskEntity taskEntity = taskEntityService.getInfoByKeyId(renewal.getId());
        int stepNo = taskEntity.getStepNo();
        String isEdit =  isEdit(renewal.getId());
        model.addAttribute("isEdit", isEdit);
        model.addAttribute("renewal", renewal);
        model.addAttribute("stepNo", stepNo);
        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);

        return "/com/renewal_read";
    }

    /**
     * 保存Model数据
     */
    public Renewal saveModel(User user, String keyId, String renewalDateStart, String renewalDateEnd,
                             String oldDateStart, String oldDateEnd, String remarks, String parentId) throws ParseException {
        Renewal renewal=null;
        if(org.apache.commons.lang.StringUtils.isBlank(keyId)){
            renewal=new Renewal();
            renewal.setCreater(user);
            renewal.setCompany(user.getCompany());
            renewal.setName("续约申请");
        }else{
            renewal=renewalService.get(keyId);
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        if(org.apache.commons.lang.StringUtils.isNotEmpty(oldDateStart)){
            renewal.setOldDateStart(sdf.parse(oldDateStart));
        }
        if(org.apache.commons.lang.StringUtils.isNotEmpty(oldDateEnd)){
            renewal.setOldDateEnd(sdf.parse(oldDateEnd));
        }
        if(org.apache.commons.lang.StringUtils.isNotEmpty(renewalDateStart)){
            renewal.setRenewalDateStart(sdf.parse(renewalDateStart));
        }
        if(org.apache.commons.lang.StringUtils.isNotEmpty(renewalDateEnd)){
            renewal.setRenewalDateEnd(sdf.parse(renewalDateEnd));
        }
        if(org.apache.commons.lang.StringUtils.isNotEmpty(remarks)){
            renewal.setRemarks(remarks);
        }
        if(org.apache.commons.lang.StringUtils.isNotEmpty(parentId)){
            renewal.setPersonnelInfo(personnelInfoService.get(parentId));
        }

        return renewal;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user,
                       @RequestParam(required = false) String keyId,
                       String renewalDateStart,
                       String renewalDateEnd,
                       String oldDateStart,
                       String oldDateEnd,
                       String remarks,
                       String parentId) throws ParseException {

        Map<String,Object> rMap=new HashMap<String,Object>();
        Renewal renewal=saveModel(user,keyId,renewalDateStart,renewalDateEnd,oldDateStart,oldDateEnd,remarks,parentId);

        if(StringUtils.isNotEmpty(keyId)){
            renewalService.update(renewal);
            rMap.put("message", "更新成功");
        } else {
            renewalService.save(renewal, "com.fz.us.oa.core.entity.com.Renewal");
            rMap.put("message", "保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 提交操作
     */
    @RequestMapping(value = "submit", method = RequestMethod.POST)
    public Object submit(@CurrentUser User user,
                         @RequestParam(required = false) String keyId,
                         String renewalDateStart,
                         String renewalDateEnd,
                         String oldDateStart,
                         String oldDateEnd,
                         String remarks,
                         String parentId,
                         String curDutyId,
                         String comment) throws ParseException {

        Map<String, Object> rMap = new HashMap<String, Object>();
        Renewal renewal=saveModel(user,keyId,renewalDateStart,renewalDateEnd,oldDateStart,oldDateEnd,remarks,parentId);

        if (StringUtils.isNotEmpty(keyId)) {
            renewalService.approve(renewal, dutyService.get(curDutyId), comment);
        } else {
            renewalService.commit(renewal, "com.fz.us.oa.core.entity.com.Renewal", dutyService.get(curDutyId));
        }

        //新建异动总汇表
        AllChange allChange=new AllChange();
        allChange.setType("2");
        allChange.setRenewal(renewal);
        allChange.setPersonnelInfo(personnelInfoService.get(parentId));
        allChange.setName("续约申请");
        allChange.setCreater(user);
        allChange.setCompany(user.getCompany());
        allChange.setIsFinished("0");
        allChangeService.commit(allChange, "com.fz.us.oa.core.entity.com.AllChange", dutyService.get(curDutyId));

        renewal.setAllChange(allChange);
        renewalService.update(renewal);

        if(renewal.getProcessState().name().equals("Finished")){
            doFinished(renewal,parentId);
        }


        rMap.put("message", "提交成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment, String parentId){
        Map<String,Object> rMap=new HashMap<String,Object>();
        Renewal renewal = renewalService.get(keyId);
        renewalService.approve(renewal, dutyService.get(curDutyId), comment);

        //归档后...
        if(renewal.getProcessState().name().equals("Finished")){
            doFinished(renewal,parentId);
        }
        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    public void doFinished(Renewal renewal,String parentId){
        //完成总汇表
        AllChange allChange=renewal.getAllChange();
        allChange.setIsFinished("1");
        allChangeService.update(allChange);

        //修改用工信息
        PersonnelUse personnelUse=personnelInfoService.get(parentId).getPersonnelUse();
        personnelUse.setContractDateStart(renewal.getRenewalDateStart());
        personnelUse.setContractDateEnd(renewal.getRenewalDateEnd());
        personnelUseService.update(personnelUse);

        //修改人事信息主表 是否即将到期
        PersonnelInfo personnelInfo=personnelInfoService.get(parentId);
        Date now=new Date();
        if(DateUtils.truncatedCompareTo(DateUtils.addDays(renewal.getRenewalDateEnd(), -30), now, Calendar.DATE)<0){
            personnelInfo.setExpire(true);
        }else{
            personnelInfo.setExpire(false);
        }
        personnelInfoService.saveEntity(personnelInfo);

        //发送提醒
        Remind remind = new Remind();
        remind.setUser(personnelInfoService.get(parentId).getUser());
        remind.setBussinessKey("renewal");
        remind.setKeyId(renewal.getId());
        remind.setContent("您的续约申请已通过，请查看");
        remindService.save(remind);
    }

    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Renewal renewal = renewalService.get(keyId);
            renewalService.back(renewal, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Renewal renewal = renewalService.get(keyId);
            renewalService.deny(renewal, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

}
